<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Cliente extends CI_Controller {
    	
    function Cliente (){
        parent::__construct();
        
        if(!$this->session->userdata('logged')){
        	redirect('login');
        }
 	}
	
	public function index (){
	    // Load open transports
	    $this->load->model('client_model');
	    $data['clientes'] = $this->client_model->get(false);
	 
	    $data['page_title']  = "Clientes";
	 
	    // Load View
	    $this->template->show('cliente/list', $data);
	}
	
	public function add (){
		$data = array(
			'page_title'	=> 'Novo Cliente',
			'nome'			=> '',
			'telefone' 		=> '',
			'email' 		=> '',
			'cpf'			=> '',
			'endereco' 		=> '',
			'cep' 			=> '',
			'cidade' 		=> '',
			'estado' 		=> '',
			'bairro' 		=> '',
		);
		
	    $this->template->show('cliente/add', $data);
	}
	 
	public function edit ($id){
		$this->load->model('client_model');
	    $data = $this->client_model->get($id);
	 
	    // $data['password'] = '';
	    $data['page_title']  = "Editar Cliente - ".$data['nome'];
	 
	    $this->template->show('cliente/add', $data);
	}
	
	public function remove ($id){
	    $this->load->model('client_model');
	    $this->client_model->delete($id);
	 
	    redirect('cliente');
	}
	
	public function save(){
        if($this->input->post('cancel') !== FALSE){
        	redirect('cliente');
        }
            
		$client_id = $this->input->post('id');
        
        $this->load->library('form_validation');
		
		$this->form_validation->set_rules('nome', 'Nome', 'required|ucwords');
        $this->form_validation->set_rules('telefone', 'Telefone', 'trim|required');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
        $this->form_validation->set_rules('cpf', 'CPF', 'required');
        
        if($this->form_validation->run() === false)  {
            $this->error = true;
            
            if ($client_id){
                $this->edit ($client_id);
            } else {
                $this->add ();
			}
			
            return;
        }
        
        $this->load->model('client_model');
        
        $sql_data = array(
        	'nome'			=> $this->input->post('nome'),
			'telefone' 		=> $this->input->post('telefone'),
			'email' 		=> $this->input->post('email'),
			'cpf'	 		=> $this->input->post('cpf'),
			'endereco' 		=> $this->input->post('endereco'),
			'cep' 			=> $this->input->post('cep'),
			'cidade' 		=> $this->input->post('cidade'),
			'estado' 		=> $this->input->post('estado'),
			'bairro' 		=> $this->input->post('bairro'),
        );
        
        if ($client_id){
            $this->client_model->update($client_id,$sql_data);
        } else {
            $this->client_model->create($sql_data);
		}

        redirect('cliente');
    }
 
}